import { FILE_STATUS } from '@/constants'
import { PageResVO } from '@/types/request'
import request from '@/util/http/index'

interface HFilePageReq extends PageResVO {}
/**
 * 查询文件列表
 */
export const queryFileList = async (params: HFilePageReq) => {
  return await request.get({
    url: '/crc/svg/page',
    params
  })
}

/**
 * 保存新文件
 */
export const createGraphFile = async (data: HFileMeta) => {
  return await request.post({
    url: '/crc/svg/create',
    data
  })
}

/**
 * 获取文件详情
 */
export const getGraphFileMeta = async (id: number) => {
  return await request.get({
    url: '/crc/svg/get',
    params: { id }
  })
}
/**
 * 更新文件信息
 */
export const updateGraphFile = async (data: HFileMeta) => {
  return await request.put({
    url: '/crc/svg/update',
    data
  })
}

/**
 * 修改文件状态
 */
export const updateGraphFileStatus = async (id: number, status: FILE_STATUS) => {
  return await request.put({
    url: '/crc/svg/updateStatus',
    params: {
      id,
      status
    }
  })
}

/**
 * 删除文件信息
 */
export const deleteGraphFile = async (id: number) => {
  return await request.delete({
    url: '/crc/svg/delete',
    params: { id }
  })
}
/**
 * 上传文件
 */
export const uploadXml = async (xml: string, fileMeta: HFileMeta) => {
  const blob = new Blob([xml], { type: 'application/xml;charset=utf-8' })
  const formData = new FormData()
  formData.append('file', blob, fileMeta?.name || '')
  formData.append('path', fileMeta?.name || '')
  const url = import.meta.env.VITE_UPLOAD_URL
  return await request.upload({
    url,
    data: formData
  })
}

/**
 * 上传图片
 * @param buf
 * @param fileMeta
 * @returns
 */
export const uploadImage = async (buf: ArrayBuffer, fileMeta: HFileMeta) => {
  const blob = new Blob([buf], { type: 'image/*' })
  const formData = new FormData()
  formData.append('file', blob, fileMeta?.name || '')
  formData.append('path', fileMeta?.name || '')
  const url = import.meta.env.VITE_UPLOAD_URL
  return await request.upload({
    url,
    data: formData
  })
}

/**
 * 下载文件
 * @param path
 * @returns
 */
export const requestFile = async (path: string) => {
  return await fetch(path)
    .then((response) => response.text())
    .catch((error) => {
      console.error('Error loading SVG file:', error)
    })
}

/**
 * 查询真正的文件信息
 * @param params
 * @returns
 */
export const getFilePage = async (params: { path: string; type?: string; createTime?: number }) => {
  return await request.get({
    url: '/infra/file/page',
    params
  })
}

/**
 * 删除文件
 */
export const deleteFile = async (id: number) => {
  return await request.delete({
    url: '/infra/file/delete',
    params: { id }
  })
}
